import threading
import time
import random


class T(threading.Thread):

    def __init__(self, tid):
        self.tid = tid
        threading.Thread.__init__(self)

    def run(self):
        ifile = open('/dev/urandom', 'rb')
        size = 4096
        while True:
            data = ifile.read(size)
            if flags[self.tid].is_set():
                print('thread #%s exiting' % self.tid)
                break


if __name__ == '__main__':

    amount = 2
    flags = [threading.Event() for i in range(amount)]
    threads = []

    for i in range(amount):
        thread = T(i)
        thread.start()
        threads.append(thread)

    time.sleep(3)

    for f in flags:
        f.set()

    for thread in threads:
        thread.join()

    print('Main thread exiting.')
